import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { List, ListItem, ListItemText, Box } from '@mui/material';
import { getAdminMenus } from '../../api/apiFunctions';

const AdminMenuList = () => {
  const [adminMenuItems, setAdminMenuItems] = useState([]);
  const navigate = useNavigate();

  // 从 Redux 中获取 isAuthenticated 状态
  const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);

  useEffect(() => {
    if (isAuthenticated) {
      const fetchMenus = async () => {
        try {
          const response = await getAdminMenus();
          setAdminMenuItems(response.data);
        } catch (error) {
          console.error('获取菜单失败:', error);
        }
      };

      fetchMenus();
    } else {
      navigate('/login'); // 未登录跳转到登录页
    }
  }, [isAuthenticated, navigate]);

  const handleNavigate = (path) => {
    navigate(path);
  };

  return (
    <Box sx={{ overflow: 'auto' }}>
      <List>
        {adminMenuItems.length > 0 ? (
          adminMenuItems.map((item, index) => (
            <ListItem button key={index} onClick={() => handleNavigate(item.path)}>
              <ListItemText primary={item.name} />
            </ListItem>
          ))
        ) : (
          <ListItem>
            <ListItemText primary="暂无菜单" />
          </ListItem>
        )}
      </List>
    </Box>
  );
};

export default AdminMenuList;
